package com.itouchtv.yang.core.tools;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;

/**
 *解析XML，获取页面元素
 **/
public class AnalysisXml {
    private Document document;
    private Element root;

    private void loadXml(String file) {
        SAXReader reader = new SAXReader();
        //Log.logger.info("读取XML:" + file);
        try {
            document = reader.read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
            Log.logger.error("找不到目标文件:" + file);
            System.exit(-1);
        }
        root = document.getRootElement();
    }

    public Document getDocument(String file){
        SAXReader reader = new SAXReader();
        //Log.logger.info("读取XML:" + file);
        try {
            return document = reader.read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
            Log.logger.error("找不到目标文件:" + file);
            return null;
        }
    }

    public String getPageName(String url){
        String path = ClassPath.getClassPath();

        loadXml(path+"library/Library.xml");

        if (root==null) {
            Log.logger.error("没有找到根元素，错误的文档");
        } else for (Element element : root.elements()) {
            String s = element.attributeValue("url");
            if (s.equals(url)) {
                return element.attributeValue("name");
            }
        }
        return null;
    }

    //查找某个节点下子元素集合
    public List<Element> getPageElements(String pageName) {
        String path = ClassPath.getClassPath();
        loadXml(path+"library/Library.xml");
        Log.logger.info("开始查找" + pageName + "页面下的元素集合");
        if (root==null) {
            Log.logger.error("没有找到根元素，错误的文档");
        } else for (Element element : root.elements()) {
            if (element.attributeValue("name").equals(pageName)) {
                Log.logger.info("查找" + pageName + "页面下的元素集合成功");
                return element.elements();
            }
        }
        Log.logger.error("没有找到名为：" + pageName + "的页面");
        return null;
    }
}
